<template>
  <div class="app-container">
    <el-card class="heardCard" shadow="never">
      <el-form ref="form" :inline="true" :model="quaryParams">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item
              label="车辆类型"
              label-width="85px"
              prop="truckTypeId"
            >
              <el-select
                ref="select"
                v-model="quaryParams.truckTypeId"
                placeholder="请选择"
                style="width: 300px"
                clearable
              >
                <el-option
                  v-for="item in carTypeList"
                  :key="item.id"
                  style="width: 100%"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="车牌号码:"
              label-width="85px"
              prop="licensePlate"
            >
              <el-input
                v-model="quaryParams.licensePlate"
                placeholder="请输入车牌号码"
                clearable
                style="width: 300px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="search">搜索</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="nav_change">
      <el-tag
        :class="{ active: index === 0 }"
        @click="toggleTab(0)"
      >全部<b>{{ carCount[1] * 1 + carCount[0] * 1 || 0 }}</b></el-tag>
      <el-tag
        :class="{ active: index === 1 }"
        @click="toggleTab(1)"
      >可用<b>{{ carCount[1] || 0 }}</b></el-tag>
      <el-tag
        :class="{ active: index === 2 }"
        @click="toggleTab(2)"
      >停用<b>{{ carCount[0] || 0 }}</b></el-tag>
    </el-card>

    <el-card shadow="never">
      <el-button type="primary" @click="addCar">新增车型</el-button>
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        stripe
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="index" label="序号" width="50px" align="center">
          <template #default="slot">
            {{
              (quaryParams.page - 1) * quaryParams.pageSize + slot.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="licensePlate" label="车牌号码" align="center" />
        <el-table-column prop="truckTypeName" label="车辆类型" align="center" />
        <el-table-column prop="driverNum" label="司机数量" width="100" align="center" />
        <el-table-column prop="status" label="车辆状态" align="center">
          <template #default="{ row }">
            <span v-if="row.workStatus" class="usable carStatus">可用</span>
            <span v-else class="disable carStatus">停用</span>
          </template>
        </el-table-column>
        <el-table-column prop="deviceGpsId" label="GPS设备ID" align="center" />
        <el-table-column
          prop="allowableLoad"
          label="实载重量(T)"
          align="center"
        />
        <el-table-column
          prop="allowableVolume"
          label="实载体积(方)"
          align="center"
        />
        <el-table-column label="操作" width="180px" align="center">
          <template #default="{ row }">
            <el-button
              class="anNiu"
              size="mini"
              type="text"
              @click="handleVehicleDetail(row.id)"
            >查看详情</el-button>
            <div class="line" />
            <el-button
              v-if="!row.workStatus"
              style="color: #419eff"
              size="mini"
              type="text"
              @click="handleStatus(row)"
            >启用</el-button>
            <el-button
              v-else
              size="mini"
              type="text"
              @click="handleStatus(row)"
            >停用</el-button>
            <!-- <el-button size="mini" type="text" @click="handleStatus(row)">{{ row.workStatus === 0?'停用':'启用' }}</el-button> -->
            <div class="line" />
            <el-button
              class="anNiu"
              size="mini"
              type="text"
              @click="fnDeploy(row)"
            >配置司机</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        align="center"
        :current-page.sync="quaryParams.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="quaryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 添加和编辑弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      append-to-body
      width="650px"
      @close="fnCancel"
    >
      <el-form
        ref="formdialog"
        label-width="110px"
        :model="formdialog"
        :rules="rules"
      >
        <el-form-item label="车辆类型" prop="truckTypeId">
          <el-select v-model="formdialog.truckTypeId">
            <el-option
              v-for="item in carTypeList"
              :key="item.id"
              style="width:100%"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="车牌号码" prop="licensePlate">
          <el-input
            v-model="formdialog.licensePlate"
            placeholder="请输入车牌号"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="GPS设备ID" prop="deviceGpsId">
          <el-input
            v-model="formdialog.deviceGpsId"
            placeholder="请输入GPS设备ID"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item style="text-align: center; margin-bottom: 38px">
          <el-button type="primary" @click="fnOK">确定</el-button>
          <el-button @click="fnCancel">取消</el-button></el-form-item>
      </el-form>
    </el-dialog>
    <!-- 车辆启用弹框 -->
    <el-dialog
      title="车辆启用"
      class="hint"
      width="30%"
      :visible.sync="showStarStatus"
    >
      <h2>确定要启用吗？车辆启用需满足以下条件:</h2>
      <div class="term">
        <span><i>1</i>车辆信息已完善</span>
        <span><i>2</i>绑定司机>=2,且有排班</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showStarStatus = false">取 消</el-button>
        <el-button type="primary" @click="starCar">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 车辆停用弹框 -->
    <el-dialog
      title="车辆停用"
      class="hint"
      width="30%"
      :visible.sync="showStopStatus"
    >
      <h2>确定要停用吗？车辆停用需满足以下条件:</h2>
      <div class="term">
        <span><i>1</i>车辆当前无运输任务</span>
        <span><i>2</i>车辆无关联运输线路</span>
        <span class="color">注: 停用后司机将自动解除绑定</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showStopStatus = false">取 消</el-button>
        <el-button type="primary" @click="stopCar">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 车辆配置弹框1:提示弹窗 -->
    <el-dialog
      class="hint"
      title="车辆配置"
      width="30%"
      :visible.sync="showHintDialog"
    >
      <h2>配置司机需满足以下条件:</h2>
      <div class="term">
        <span><i>1</i>车辆信息已完善</span>
        <span><i>2</i>车辆无未完成运输任务</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showHintDialog = false">取 消</el-button>
        <el-button type="primary" @click="fnHintOK">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 车辆配置弹框的确定:配置司机 -->
    <!-- 主要弹框 -->
    <el-dialog
      width="650px"
      class="primary"
      title="配置司机"
      :visible.sync="showDialog"
    >
      <el-form :model="carModalInfo" style="padding: 21px 52px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="车牌号：">
              <span>{{ carModalInfo.licensePlate }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="车型：">
              <span>{{ carModalInfo.truckTypeName }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="车辆状态：">
              <span class="state" :class="{usable:carModalInfo.status}">{{ carModalInfo.status === 1 ? "可用" : "停用" }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="实载重量：">
              <span>{{ carModalInfo.allowableLoad }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="实载体积：">
              <span>{{ carModalInfo.allowableVolume }}</span>
            </el-form-item>
          </el-col>
        </el-row></el-form>
      <div class="select">
        <label>配置司机:</label>
        <el-select
          v-model="carModalInfo.name"
          style="width: 300px"
          size="medium"
          multiple
          @change="bindingDriver"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            style="width: 100%"
            :label="item.name"
            :value="{ value: item.id, info: item }"
          />
        </el-select>
      </div>
      <el-table
        v-loading="bindingLoading"
        style="width: 600px; margin-left: 21px"
        :data="bindingDriverData"
      >
        <el-table-column label="序号" type="index" width="211" />
        <el-table-column label="司机名称" width="211" prop="name" />
        <el-table-column align="center" label="操作" width="160">
          <template #default="{ row }">
            <router-link
              class="anNiu"
              :to="{
                path: '/user/driver-detail',
                query: {
                  id: row.userId,
                },
              }"
            >查看</router-link>
            <div class="line" />
            <el-button
              size="mini"
              type="text"
              style="color: #f56c6c"
              @click="fnDel(row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="driverOk">确 认</el-button>
        <el-button @click="fnClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCarListPage,
  getCarTypeList,
  addCarList,
  getDriverListByCar,
  driverOkApi,
  stopCar,
  starCar,
  getCarCountAPI,
  getUnBindingDrivers
} from '@/api/car'
export default {
  name: 'Car',
  data() {
    return {
      quaryParams: {
        page: 1,
        pageSize: 10,
        workStatus: ''
      },
      tableData: [],
      total: 0,
      index: 0,
      // 下拉列表数据
      carTypeList: [],
      open: false,
      title: '',
      formdialog: {
        licensePlate: '',
        deviceGpsId: '',
        truckTypeId: ''
      },
      // 车辆配置弹框
      showHintDialog: false,
      // 确定弹框
      showDialog: false,
      // 车辆配置信息
      carModalInfo: {},
      // 车辆配置列表信息
      truckId: '', // 当前选中id
      loading: false, // 加载
      carCount: {}, // 车辆统计数
      rules: {
        licensePlate: [
          { required: true, message: '车牌号不能为空', trigger: 'blur' },
          { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]$/, message: '请输入正确的车牌号', trigger: ['blur', 'change'] }
        ],
        deviceGpsId: [
          { required: true, message: 'GPS设备ID不能为空', trigger: 'blur' }
        ]
      },
      currentData: {},
      options: [], // 配置司机数据
      bindingDriverData: [], // 绑定司机信息
      showStarStatus: false, // 车辆启用
      showStopStatus: false, // 车辆停用
      statusId: '',
      bindingLoading: false
    }
  },
  created() {
    this.getList()
    this.getCarTypeList()
    this.getCarCount()
  },
  methods: {
    // 切换 全部||可用||停用
    toggleTab(index) {
      this.index = index
      this.quaryParams.page = 1
      this.quaryParams.pageSize = 10
      switch (index) {
        case 1:
          this.quaryParams.workStatus = 1
          break
        case 2:
          this.quaryParams.workStatus = 0
          break
        default:
          this.quaryParams.workStatus = ''
          break
      }
      this.getList()
    },
    // 获取全部车辆条数(可用||停用)
    async getCarCount() {
      const res = await getCarCountAPI()
      this.carCount = res
    },
    // 获取全部列表
    async getList() {
      this.loading = true
      const res = await getCarListPage(this.quaryParams)
      console.log(res)
      this.tableData = res.items
      this.total = res.counts * 1
      this.loading = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },

    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.quaryParams.page = val
      this.getList()
    },

    async getCarTypeList() {
      const res = await getCarTypeList()
      console.log(res)
      this.carTypeList = res
    },
    search() {
      this.quaryParams.page = 1
      this.getList()
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.getList()
    },
    // 新增按钮
    addCar() {
      this.title = '新增车辆'
      this.open = true
    },
    // 确定按钮
    async fnOK() {
      await this.$refs.formdialog.validate()
      await addCarList(this.formdialog)
      this.$message.success('新增角色成功')
      this.getList()
      this.fnCancel()
    },
    // 取消
    fnCancel() {
      this.$refs.formdialog.resetFields() // 重置表单数据
      this.open = false // 关闭弹层
    },
    // 查看详情按钮
    // 车辆详情
    handleVehicleDetail(id) {
      console.log(id)
      this.$router.push({
        path: '/car/carDetail',
        query: { id }
      })
    },
    // 车辆配置按钮
    fnDeploy(row) {
      this.currentData = row
      this.showHintDialog = true
    },
    // 确定按钮
    fnHintOK() {
      this.showHintDialog = false
      this.showDialog = true
      this.carModalInfo = this.currentData
      this.getUnBindingDrivers()
      this.getDriverListByCar()
    },

    async getUnBindingDrivers() {
      const res = await getUnBindingDrivers()
      console.log(res)
      this.options = res
    },
    // 获取绑定司机
    async getDriverListByCar() {
      this.bindingLoading = true
      const res = await getDriverListByCar(this.currentData.id)
      this.bindingDriverData = res
      this.carModalInfo.name = res.map(item => item.name)
      this.bindingLoading = false
    },
    // 选中的司机
    bindingDriver(val) {
      this.bindingDriverData = []
      val.forEach((item) => {
        this.bindingDriverData.push(item.info)
      })
    },
    // 删除选中司机
    fnDel(row) {
      this.bindingDriverData = this.bindingDriverData.filter(item => item !== row)
      this.carModalInfo.name = this.carModalInfo.name.filter(item => item !== row.name)
    },
    // 配置司机点击确定
    async driverOk() {
      await driverOkApi({
        driverIds: [this.carModalInfo.userId],
        truckId: this.options[0]?.id || ''
      })
      this.$message.success('配置成功')
      this.fnClose()
    },
    fnClose() {
      this.showDialog = false
      this.options = []
    },
    // 车辆启用停用
    handleStatus(row) {
      this.statusId = row.id
      if (row.workStatus === 0) {
        this.showStarStatus = true
      } else {
        this.showStopStatus = true
      }
    },
    // 停用的确定
    async stopCar() {
      try {
        await stopCar(this.statusId)
      } catch (error) {
        console.log(error)
      }
      this.showStopStatus = false
    },
    // 启用的确定
    async starCar() {
      try {
        await starCar(this.statusId)
      } catch (error) {
        console.log(error)
      }
      this.showStarStatus = false
    }
  }
}
</script>
<style>
.el-select-dropdown {
  width: 0px;
}
</style>
<style lang="scss" scoped>
.el-card {
  margin-bottom: 20px;
}
span {
  display: inline-block;
  padding-left: 20px;
  width: 120px;
  font-size: 15px;
}
.el-table {
  margin-top: 10px;
  border: 1px solid #ebeef5;
  :deep(.el-table__header th){
      background-color: #f8faff;
  }
}

.heardCard {
  height: 90px;
}
//  ::v-deep .el-select-dropdown{
//     width:100px;
//   }
.liCard {
  height: 48px;
}

div {
  line-height: 12px;
}
:deep(.el-dialog) {
  overflow: hidden;
  .el-dialog__header {
    background-color: #f3f4f7;
  }
  .el-dialog__body {
    padding: 0;
  }

  .el-form {
    padding: 40px 50px 0 20px;
    .el-form-item {
      width: 100%;
      display: flex;
      .el-form-item__content {
        flex-grow: 1;
        margin-left: 6px !important;
        color: #818693;
        div {
          width: 100% !important;
        }
        .state{
          background-color: #e15536;
          width: calc(2em + 20px);
          text-align: center;
          line-height: 20px;
          color: #fff;
          font-size: 12px;
          border-radius: 10px;
        }
        .usable{
          background-color: #37c608;
        }
      }
    }
  }
  .dialog-footer {
    margin: 10px 0;
  }
}
li {
  display: inline-block;
  padding-left: 40px;
  padding-right: 40px;
  font-size: 14px;
}
.el-pagination {
  font-size: 18px;
  margin: 20px;
}
.nav_change {
  margin-top: 20px;
  margin-bottom: 20px;
  height: 48px;
  ::v-deep .el-card__body {
    padding: 0;
    .el-tag {
      padding: 0;
      height: 48px;
      width: 120px;
      line-height: 48px;
      text-align: center;
      background-color: #f8faff;
      color: #333;
      font-size: 14px;
      cursor: pointer;
      border: 0;
    }
  }
}
.active {
  background-color: #ffeeeb !important;
  color: #e15536 !important;
}

.primary {
  :deep(.el-dialog) {
    border-radius: 10px;
    .el-dialog__footer {
      text-align: center;
    }
    .el-form {
      margin: 20px 20px 0px 20px;
    }
    .el-form-item {
      height: 13px;
      .el-form-item__label {
        font-size: 14px;
        font-weight: 400;
        color: #20232a;
        padding: 0;
      }
      span {
        padding-left: 0;
        font-weight: 400;
      }
    }
  }
}
.select {
  margin: 20px 8px;
  label {
    margin-left: 15px;
    margin-right: 10px;
  }
}
// 提示弹框
.hint {
  :deep(.el-dialog__body) {
    padding: 10px 15px 10px 24px;
    h2 {
      font-size: 14px;
      font-weight: 500;
      color: #332929;
    }
    .term {
      display: flex;
      flex-wrap: wrap;
      span {
        width: 50%;
        padding-left: 0px;
        margin-bottom: 0.6em;
        i {
          font-style: normal;
          border: 1px solid #edf0f6;
          display: inline-block;
          width: 1.25em;
          height: 1.25em;
          text-align: center;
          background-color: #fafcff;
          line-height: 1.25;
          border-radius: 50%;
        }
      }
    }
  }
}
.line {
  display: inline-block;
  width: 1px;
  height: 1em;
  margin: 0 8px;
  vertical-align: middle;
  background-color: #dcdfe6;
}
.el-table {
  border: 1px solid #ebeef5;
  .carStatus {
    font-size: 13px;
    &::before {
      content: "";
      display: inline-block;
      margin-right: 6px;
      width: 6px;
      height: 6px;
      border-radius: 50%;
    }
  }
  .usable::before {
    background-color: #1dc779;
  }
  .disable::before {
    background-color: #e15536;
  }
}
.color {
  display: block;
  margin-top: 6px;
  color: #ffc94e;
}
.anNiu {
  color: #419eff;
  font-size: 12px;
}
</style>
